package com.twfpro.httprequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * HTTP请求类
 * 
 * @author 高文
 *
 */
public class HttpRequest
{
	private OkHttpClient client;
	private Builder requestBuilder;
	private RequestBody body;

	public HttpRequest()
	{
		client = new OkHttpClient.Builder().connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS)
				.writeTimeout(120, TimeUnit.SECONDS).build();
		requestBuilder = new Request.Builder();
	}

	public HttpRequest url(String url)
	{
		requestBuilder.url(url);
		return this;
	}

	public HttpRequest headers(HashMap<String, String> headers)
	{
		requestBuilder.headers(Headers.of(headers));
		return this;
	}

	public HttpRequest header(String name, String value)
	{
		requestBuilder.header(name, value);
		return this;
	}

	public HttpRequest addHeader(String name, String value)
	{
		requestBuilder.addHeader(name, value);
		return this;
	}

	public HttpRequest get()
	{
		requestBuilder.get();
		return this;
	}

	public HttpRequest post(byte[] content, String contentType)
	{
		if (contentType == null || contentType.isEmpty())
		{
			body = RequestBody.create(null, content);
		}
		else
		{
			body = RequestBody.create(MediaType.get(contentType), content);
		}
		requestBuilder.post(body);
		return this;
	}

	public HttpRequest post(String content, String contentType)
	{
		if (contentType == null || contentType.isEmpty())
		{
			body = RequestBody.create(null, content);
		}
		else
		{
			body = RequestBody.create(MediaType.get(contentType), content);
		}
		requestBuilder.post(body);
		return this;
	}

	public HttpRespone send() throws IOException
	{
		Response respone = client.newCall(requestBuilder.build()).execute();
		return new HttpRespone(respone);
	}

	public static void main(String[] args)
	{
		// 简单使用示范
		HttpRequest httpRequest = new HttpRequest();
		httpRequest.url("https://passport-api.wangyuan.com/passport/login").post("内容", "contType");
		try
		{
			HttpRespone httpRespone = httpRequest.send();
			httpRespone.stringBody();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
